import os
from datetime import datetime
import shutil
import time
import zipfile
import requests
import yaml

with open('config.yml', 'r', encoding='utf-8') as f:
    config = yaml.safe_load(f)

class DownloadHuiwuFile:
    def __init__(self, huiwuCookie, rKey, fileTitle):
        self.huiwuCookie = huiwuCookie
        self.rKey = rKey
        self.fileTitle = fileTitle
        self.filePath = config['home_dir'] + '/'
    
    def doDownload(self):
        # 获取今年的年份
        year = datetime.now().year
        # 创建年份文件夹
        filePath = self.filePath + str(year)
        os.makedirs(filePath, exist_ok=True)
        # 创建文件夹
        filePath = filePath + '/' + time.strftime("%m", time.localtime())
        os.makedirs(filePath, exist_ok=True)
        # 创建日期文件夹
        file_name_date = time.strftime("%m%d", time.localtime()) # 0509
        folder_path_date = filePath + "/" + file_name_date
        os.makedirs(folder_path_date, exist_ok=True)
        
        # 获取当前文件夹内的所有文件夹的名字，提取名字的前两位并转成数字，取最大的那个数字
        os.chdir(folder_path_date)
        existing_folders = os.listdir()
        max_num = 0
        if existing_folders:
            for folder in existing_folders:
                # 过滤掉不是数字开头的文件夹
                if not folder.split("-")[0].isdigit():
                    continue
                num = int(folder.split("-")[0])
                if num > max_num:
                    max_num = num
                if self.fileTitle[:79] in folder.split("-")[1]:
                    print(f"{self.fileTitle[:79]} 已存在")
                    max_num = num - 1
                    break
        # 创建正文文件夹。处理文件名太长的问题 名字最多83个汉字
        file_path = filePath + "/" + file_name_date + "/" + f"{max_num+1:02d}-" + self.fileTitle[:83]
        # 如果存在就删除源文件，不管是否为空
        if os.path.exists(file_path):
            shutil.rmtree(file_path, ignore_errors=True)

        os.makedirs(file_path, exist_ok=True)
        self.filePath = file_path
        return self.getMtFile()
    
    def getMtFile(self):
        os.chdir(self.filePath)
        try:
            config['huiwu_headers']['Cookie'] = self.huiwuCookie
            # 发送HTTP GET请求，并设置请求头
            response = requests.get(config['huiwu_url'] + "/getMtFile.html?mtrkey=" + self.rKey, stream=True, headers=config['huiwu_headers'], verify=False)
            response.raise_for_status()  # 检查请求是否成功
            response_content_type = response.headers.get('Content-Type', '')

            if "application/octet-stream" in response_content_type :
                # 以二进制写入模式保存文件
                with open(self.fileTitle[:79] + ".pdf", 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:  # 过滤掉保持连接的新块
                            f.write(chunk)
                print(f"{self.fileTitle[:79]} 已保存正文")
            else:
                print(f"{self.fileTitle[:79]} 无正文")

            #下载zip附件
            response = requests.get(config['huiwu_download_url'] + self.rKey, stream=True, headers=config['huiwu_headers'], verify=False)
            response.raise_for_status()  # 检查请求是否成功
            # print(response.headers)
            response_content_type = response.headers.get('Content-Type', '')
            if "application/zip" in response_content_type :
                with open("全部附件.zip", "wb") as f:
                    f.write(response.content)
                print(f"{self.fileTitle[:79]} 已保存附件")
                #解压zip
                try:
                # 确保目标目录存在
                    os.makedirs("全部附件", exist_ok=True)
                    # 打开 ZIP 文件
                    with zipfile.ZipFile("全部附件.zip", 'r') as zip_ref:
                        # 解压所有文件到目标目录
                        zip_ref.extractall("全部附件")
                    os.remove("全部附件.zip")
                    # 成功解压后执行wps转为docx
                    self.convertWpsToDocx()
                except zipfile.BadZipFile:
                    print("错误：文件不是有效的 ZIP 文件")
                except Exception as e:
                    print(f"解压文件时发生错误: {e}")
            else:
                print(f"{self.fileTitle[:79]} 无附件")
            return True
        except Exception as e:
            print(f"下载失败: {e}")
            return False
    
    def convertWpsToDocx(self):
        # 定位到指定目录
        os.chdir(self.filePath + "/全部附件")
        
        # 将该目录下的所有wps后缀重命名为docx
        for wps_file in os.listdir():
            if wps_file.endswith(".wps"):
                docx_file = os.path.splitext(wps_file)[0] + '.doc'
                os.rename(wps_file, docx_file)
    
# if __name__ == "__main__":
#     # 禁用SSH警告
#     urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
#     dowhwf = DownloadHuiwuFile('sslhw_zw=HW-2; PHPSESSID=afcffce816a1ddbba8ef048fc139f4fc', "6D454AA4-EB16-D87E-7BA7-5EDF04D38F5D", "关于梳理报送支持怀集发展政策措施的通知")
#     dowhwf.doDownload()
